<template>
  <audio controls preload="true" v-if="url" :ref="player" :src="attachImageUrl(url)" @canplay="startPlay"
    @ended="ended"></audio>
</template>

<script lang="ts">
import { defineComponent, computed, watch, ref } from "vue";
import { useGlobalStore } from '@/store';
import { HttpManager } from "@/api";

export default defineComponent({
  setup() {
    const store = useGlobalStore();
    const divRef = ref<HTMLAudioElement>() as any;
    const player = (el) => {
      divRef.value = el;
    };

    const url = computed(() => store.url); // 音乐链接
    const isPlay = computed(() => store.isPlay); // 播放状态
    // 监听播放还是暂停
    watch(isPlay, () => {
      togglePlay();
    });

    // 开始/暂停（增强健壮性版本）
    async function togglePlay() {
      try {
        const player = divRef.value as HTMLAudioElement | null;
        if (!player) {
          console.error('Audio element not initialized');
          return;
        }

        // 使用可选链操作符和空值合并运算符
        if (isPlay.value) {
          await player.play().catch((e) => {
            console.error('Play failed:', e);
            store.setIsPlay(false); // 播放失败时回滚状态
          });
        } else {
          player.pause();
          // 保存当前播放进度到store
          store.setCurrentTime(player.currentTime);
        }
      } catch (error) {
        console.error('Playback error:', error);
        store.setIsPlay(false); // 确保状态同步
        // 可以添加错误提示逻辑（需要与UI组件配合）
      }
    }

    // 获取歌曲链接后准备播放
    function startPlay() {
      divRef.value.play();
    }
    // 音乐播放结束时触发
    function ended() {
      store.setIsPlay(false);
    }
    return {
      url,
      isPlay,
      player,
      startPlay,
      ended,
      attachImageUrl: HttpManager.attachImageUrl,
    };
  },
});
</script>

<style>
audio {
  display: none;
}
</style>
